

import 'package:flutter/material.dart';

/// 标签模型 - Tag Model
/// 表示一个标签对象，包含标签的基本信息和使用统计
class TagModel {
  /// 标签 ID - Tag ID
  final String id;
  /// 标签名称 - Tag name
  final String name;
  /// 标签颜色 - Tag color (hex color code)
  final String color;
  /// 标签描述 - Tag description
  final String description;
  /// 创建时间 - Created time
  final DateTime createdAt;
  /// 使用次数 - Usage count
  final int usageCount;
  /// 元数据 - Metadata
  final Map<String, dynamic> metadata;

  TagModel({
    required this.id,
    required this.name,
    this.color = '#2196F3',
    this.description = '',
    required this.createdAt,
    this.usageCount = 0,
    this.metadata = const {},
  });

  /// 从 JSON 创建标签模型 - Create TagModel from JSON
  TagModel.fromJson(Map<String, dynamic> json)
      : id = json['id'] ?? '',
        name = json['name'] ?? '',
        color = json['color'] ?? '#2196F3',
        description = json['description'] ?? '',
        createdAt = DateTime.parse(
            json['createdAt'] ?? DateTime.now().toIso8601String()),
        usageCount = json['usageCount'] ?? 0,
        metadata = Map<String, dynamic>.from(json['metadata'] ?? {});

  /// 转换为 JSON - Convert to JSON
  Map<String, dynamic> toJson() {
    return {
      'id': id,
      'name': name,
      'color': color,
      'description': description,
      'createdAt': createdAt.toIso8601String(),
      'usageCount': usageCount,
      'metadata': metadata,
    };
  }
}

/// TagModel 扩展方法 - TagModel Extension Methods
/// 提供业务逻辑方法，保持 Model 类的纯净性
extension TagModelExtensions on TagModel {
  /// 获取颜色值 - Get color value as Color object
  Color getColorValue() {
    try {
      // 移除 # 符号并转换为十六进制
      String colorString = color.replaceAll('#', '');
      
      // 如果是 6 位十六进制，添加 FF 作为 alpha 值
      if (colorString.length == 6) {
        colorString = 'FF$colorString';
      }
      
      // 转换为 Color 对象
      return Color(int.parse(colorString, radix: 16));
    } catch (e) {
      // 如果转换失败，返回默认蓝色
      return const Color(0xFF2196F3);
    }
  }

  /// 增加使用次数 - Increment usage count
  TagModel incrementUsage() {
    return TagModel(
      id: id,
      name: name,
      color: color,
      description: description,
      createdAt: createdAt,
      usageCount: usageCount + 1,
      metadata: metadata,
    );
  }

  /// 减少使用次数 - Decrement usage count
  TagModel decrementUsage() {
    return TagModel(
      id: id,
      name: name,
      color: color,
      description: description,
      createdAt: createdAt,
      usageCount: usageCount > 0 ? usageCount - 1 : 0,
      metadata: metadata,
    );
  }
}
